package com.tomatozq163.controller;

import com.tomatozq163.dto.NotificationDTO;
import com.tomatozq163.receiver.DeviceReceiver;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DeviceController {
    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private SimpleMessageListenerContainer messageListenerContainer;

    @Autowired
    private DirectExchange deviceExchange;

    @Autowired
    private DeviceReceiver deviceReceiver;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("createQueue")
    public String createQueue(String queueName){
        Queue queue = new Queue(queueName);
        String result = amqpAdmin.declareQueue(queue);

        System.out.println(result);

        Binding binding = BindingBuilder.bind(queue).to(deviceExchange).with(queueName);
        amqpAdmin.declareBinding(binding);

        //队列绑定事件
        messageListenerContainer.addQueueNames(queueName);

        return "ok";
    }

    @GetMapping("sendMessage")
    public void sendMessage(String queueName,String message){
        NotificationDTO dto = new NotificationDTO();
        dto.setDeviceNo(queueName);
        dto.setMessage(message);

        rabbitTemplate.convertAndSend("deviceExchange",queueName,dto);
    }

    @GetMapping("deleteQueue")
    public void deleteQueue(String queueName){
        amqpAdmin.deleteQueue(queueName);
    }
}
